<?php
/**
 * Created by PhpStorm.
 * User: 曹乐清
 * Date: 2017/4/3
 * Time: 10:56
 */

namespace Api\Controller;

use Think\Controller;

require_once './ThinkPHP/Library/Vendor/WxpayApi/lib/WxPay.Config.php';
require_once './ThinkPHP/Library/Vendor/WxpayApi/lib/WxPay.Api.php';
require_once './ThinkPHP/Library/Vendor/WxpayApi/example/WxPay.JsApiPay.php';
class WxPayController extends Controller
{
    //@todo 获取参数
    public function getUserOpenid(){
        $data=json_decode(file_get_contents("php://input"),true);
        if(isset($data['code'])){
            $wxConfig=new \WxPayConfig();
            $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$wxConfig::APPID.'&secret='.$wxConfig::APPSECRET.'&code='.$data['code'].'&grant_type=authorization_code';
            $res=cUrl($get_token_url);
            $content=$this->setParams($res['openid'],$data['id']);
            if($content['result_code']=='FAIL'){
              $this->ajaxReturn(array('meat'=>array('code'=>40021,'message'=>'调用成功'),'data'=>$content['err_code_des']));
            } else{
              $tools=new \JsApiPay();
              $res=$tools->GetJsApiParameters($content);
               $this->ajaxReturn(json_decode($res));
           }
        }
    }

    //@todo 第二步 设置参数
    private static function setParams($openId,$order_id){
        $order_info=D('orders_list')->find($order_id);
        $money=(float)$order_info['price']*100;
        $input= new \WxPayUnifiedOrder();
        $input->SetBody("实+网-网络照片");
        $input->SetOut_trade_no($order_info['orders_no']);
        $input->SetTotal_fee($money);
        $input->SetNotify_url("http://paysdk.weixin.qq.com/example/notify.php");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        header("Content-Type: application/json");
        return ($order);
    }

    //@todo 申请退款
    public function ApplyRefundAction($id,$money){
        $orders_info=D('orders_list')->find($id);
        $out_trade_no=$orders_info['orders_no'];//商户订单号
        $total_fee=$orders_info['price']*100;//订单金额
        $refund_fee=$money*100;//退款金额
        $wxConfig=new \WxPayConfig();
        $input=new \WxPayRefund();
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee($total_fee);
        $input->SetRefund_fee($refund_fee);
        $input->SetOut_refund_no($wxConfig::MCHID.date("YmdHis"));
        $input->SetOp_user_id($wxConfig::MCHID);
        $result=\WxPayApi::refund($input);
        return $result;
    }
}